import router from '@/router/index'
import { handleRouter } from './tools'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getCookie } from '@/utils/common'

// 白名单
const whiteList = ['/login'] // no redirect whitelist

let isAddRouter = false // 判断是否获取过路由
let isToPath = false // 判断是否进入页面
// 路由守卫
router.beforeEach(async (to, from, next) => {
  if (!isAddRouter) {
    // console.log(11)

    isAddRouter = true
    // 处理routerList
    handleRouter(router)
    next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  } else {
    // console.log(22)
    if (!isToPath) { // 动态加入的路由必须进过一次next()后才能获取到to中的meta beforeEach内部实际的运行流程是：11 22(无法获取to.meta) 22(可以获取到to.meta)
      next()
      isToPath = true
    } else {
      if (to.meta.noNeedLogin || !$chy.isEmpty(getCookie('user'))) {
        next()
      } else {
        Message.error('请先登录')
      }
    }
  }
})